<template>
  <!-- 已关注 -->
  <van-button
    v-if="isFollow"
    round
    size="small"
    @click="onFollow"
    :loading="followLoading"
    >已关注</van-button
  >
  <!-- 未关注 -->
  <van-button
    v-else
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    @click="onFollow"
    :loading="followLoading"
    >关注</van-button
  >
</template>

<script>
//引入通过用户id添加关注的接口
import { addFollow, deleteFollow } from "@/api/user.js";
export default {
  name: "FollowUser",
  //   自定义v-model的名称
  model: {
    prop: "isFollow",
    event: "updata-isFollow",
  },
  props: {
    // 关注状态
    isFollow: {
      type: Boolean,
      required: true,
    },
    // 关注用户Id
    autId: {
      type: [Number, String],
      required: true,
    },
  },
  data() {
    return {
      followLoading: false, //关注按钮的loading状态
    };
  },
  methods: {
    //关注与取消关注
    async onFollow() {
      // loading状态下不能进行事件的重复触发 相当于与一个节流阀的作用
      // 点击后先展示loading状态
      this.followLoading = true;
      try {
        // 如果已关注，则取消关注否则添加关注
        this.isFollow
          ? await deleteFollow(this.autId)
          : await addFollow(this.autId);
        // 更新视图
        this.$emit("updata-isFollow", !this.isFollow);
      } catch (err) {
        let message = "操作失败请稍等重试";
        if (err.response && err.response.status) {
          switch (err.response.status) {
            case 400:
              message = "自己不能关注自己";
              break;
            case 401:
              message = "用户未认证";
              break;
            case 507:
              message = "数据库错误";
              break;
          }
        }
        this.$toast(message);
      }
      //请求之后关闭loading状态
      this.followLoading = false;
    },
  },
};
</script>

<style>
</style>